package com.desire.homework;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author LittleDesire
 * @description
 * @date 2022-02-10 周四 20:02
 * @since 17
 */
public class _57_LocalDateTime转换操作 {
    public static void main(String[] args) {
        var d = LocalDateTime.now();
        System.out.println(d);
        var dt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(d.format(dt));
        System.out.println(d.toLocalDate());
        System.out.println(d.toLocalTime());


//获取秒数
        Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
//获取毫秒数
        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        System.out.println(milliSecond);

//LocalDateTime 转换 Date
        Date d2 = new Date(milliSecond);
        System.out.println(d2.getTime());
        System.out.println(System.currentTimeMillis());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(d2));

//LocalDateTime与String互转
//DateTimeFormatter 时间转字符串格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);

//字符串转时间
        String dateTimeStr = "2018-07-28 14:11:15";
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime ldt = LocalDateTime.parse(dateTimeStr, df);


//Date与LocalDateTime互转
        var da = new Date();
        var db = da.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
        System.out.println(db);
        System.out.println(db instanceof LocalDateTime);
        var dc = LocalDateTime.ofInstant(da.toInstant(), ZoneOffset.of("+8"));
        System.out.println(dc instanceof LocalDateTime);

        var dd = LocalDateTime.now();
        var de = Date.from(dd.toInstant(ZoneOffset.of("+8")));
        long ms = dd.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        var df2 = new Date(ms);
        System.out.println(dc);
        System.out.println(dd);
    }
}
